/*
 * Copyright (c) Huawei Technologies Co., Ltd. 2022-2023. All rights reserved.
 */

package com.huawei.aiservice.utils;

import com.google.gson.reflect.TypeToken;
import com.huawei.aiservice.config.GiteeConfig;
import com.huawei.aiservice.constants.GatewayConstant;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.HashMap;

/**
 * 码云登录工具
 *
 * @since 2022/11/09
 */
@Component
@Slf4j
public class GiteeAuthUtil {
    // 固定访问路径
    private static final String AUTHORIZE_URL = "https://gitee.com/oauth/authorize"
        + "?client_id=%s&redirect_uri=%s&response_type=code";

    private static final String TOKEN_URL = "https://gitee.com/oauth/token?grant_type=authorization_code&code=%s"
        + "&client_id=%s&redirect_uri=%s&client_secret=%s";

    private static final String INFO_URL = "https://gitee.com/api/v5/user?access_token=%s";

    @Autowired
    private GiteeConfig giteeConfig;

    /**
     * 调用码云接口 获得access token
     *
     * @param code 码云返回的识别码
     * @return HashMap<String, String> 响应信息
     */
    public HashMap<String, String> getToken(String code) {
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.add("Content-Type", "application/json;charset=UTF-8");
        HashMap<String, String> params = new HashMap<>();
        params.put("client_secret", giteeConfig.getClientSecret());
        String redirectUri = giteeConfig.getRedirectUri();
        String format = String.format(TOKEN_URL, code, giteeConfig.getClientId(), redirectUri,
                giteeConfig.getClientSecret());
        OkHttpClient client = new OkHttpClient().newBuilder().build();
        MediaType mediaType = MediaType.parse("application/json");
        String content = JsonUtil.toJson(params);
        RequestBody data = RequestBody.create(mediaType, content);
        Request request = new Request.Builder().url(format)
            .method("POST", data)
            .addHeader("Content-Type", "application/json")
            .build();
        HashMap<String, String> res = new HashMap<>();
        try {
            Response response = client.newCall(request).execute();
            String result = response.body().string();
            res = JsonUtil.fromJson(result, new TypeToken<HashMap<String, String>>() {}.getType());
        } catch (IOException e) {
            log.error("get access_token from gitee error");
            res.put("error_message", "get access_token from gitee error");
        }
        return res;
    }

    /**
     * 通过token获取用户信息
     *
     * @param accessToken token令牌
     * @return 返回
     */
    public static HashMap<String, String> getInfo(String accessToken) {
        HashMap<String, String> res = new HashMap<>();
        String url = String.format(INFO_URL, accessToken);
        OkHttpClient client = new OkHttpClient().newBuilder().build();
        Request request = new Request.Builder().url(url).method("GET", null).build();
        try {
            Response response = client.newCall(request).execute();
            String result = response.body().string();
            res = JsonUtil.fromJson(result, new TypeToken<HashMap<String, String>>() {}.getType());
        } catch (IOException e) {
            log.error("get info from gitee error");
            res.put("error_message", "get info from gitee error");
        }
        return res;
    }
}